
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.vng.zing.survey.thrift.server;

import com.google.gson.Gson;
import com.vng.zing.survey.data.AnswersData;
import com.vng.zing.survey.data.IDSurveyData;
import com.vng.zing.survey.data.IDSurveyHostData;
import com.vng.zing.survey.data.IDSurveyMaxData;
import com.vng.zing.survey.data.IDSurveyNewData;
import com.vng.zing.survey.data.IDUserResponseData;
import com.vng.zing.survey.data.IDUserResponseDelData;
import com.vng.zing.survey.data.IDUserResponseNoRequiData;
import com.vng.zing.survey.data.SurveyData;
import com.vng.zing.survey.data.SurveyStatsData;
import com.vng.zing.survey.data.ResponseData;
import com.vng.zing.survey.data.SurveyStatsPerDayData;
import com.vng.zing.survey.thrift.model.Action;
import com.vng.zing.survey.thrift.model.AnswerDetail;
import com.vng.zing.survey.thrift.model.AnswerItem;
import com.vng.zing.survey.thrift.model.AnswerList;
import com.vng.zing.survey.thrift.model.Error;
import com.vng.zing.survey.thrift.model.IDSurveyItem;
import com.vng.zing.survey.thrift.model.IDSurveyResult;
import com.vng.zing.survey.thrift.model.IDUserResponseItem;
import com.vng.zing.survey.thrift.model.ListShortInfoSurvey;
import com.vng.zing.survey.thrift.model.ListShortReponse;
import com.vng.zing.survey.thrift.model.QuesType;
import com.vng.zing.survey.thrift.model.Question;
import com.vng.zing.survey.thrift.model.QuestionStats;
import com.vng.zing.survey.thrift.model.ResponeDetail;
import com.vng.zing.survey.thrift.model.Response;
import com.vng.zing.survey.thrift.model.ResponseKey;
import com.vng.zing.survey.thrift.model.ShortInfoSurveyItem;
import com.vng.zing.survey.thrift.model.ShortReponse;
import com.vng.zing.survey.thrift.model.State;
import com.vng.zing.survey.thrift.model.SurveyItem;
import com.vng.zing.survey.thrift.model.SurveyItemResult;
import com.vng.zing.survey.thrift.model.SurveyStatsAllItem;
import com.vng.zing.survey.thrift.model.SurveyStatsItem;
import com.vng.zing.survey.thrift.model.SurveyStatsPerDayItem;
import com.vng.zing.survey.thrift.model.SurveyStatsResult;
import com.vng.zing.survey.thrift.model.UserType;
import com.vng.zing.survey.thrift.service.SurveyService.Iface;
import com.vng.zing.survey.thrift.utility.Utility;
import com.vng.zing.survey.utility.TimeDay;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import org.apache.thrift.TException;

/**
 *
 * @author kienpd
 */
public class SurveyServiceHandler implements Iface {

    private static Logger logger = Logger.getLogger(SurveyServiceHandler.class);

    @Override
    public IDSurveyResult newSurvey(int idUser, SurveyItem surveyItem) throws TException {

        long startTime = new Date().getTime();

        IDSurveyData dSurveyData = IDSurveyData.getInstance();
        IDSurveyResult dSurveyResult = new IDSurveyResult();
        IDSurveyItem dSurveyItem = dSurveyData.getIDSurveyItem(idUser);
        if (dSurveyItem != null && dSurveyItem.count >= 100) {

            dSurveyResult.setError(Error.MAX_COUNT_SURVEY);
            return dSurveyResult;

        }
        int maxid = IDSurveyMaxData.getInstance().incMaxIDSuvery();
        if (maxid == 0) {
            dSurveyResult.setError(Error.ERR_SYSTEM);
            return dSurveyResult;
        }

        dSurveyData.updateIDSurveyItem(idUser, maxid, Action.ADD);
        if (SurveyData.getInstance().setSurvey(maxid, surveyItem) != Error.SUCCESS) {
            dSurveyResult.setError(Error.ERR_SYSTEM);

            return dSurveyResult;
        }

        SurveyStatsItem surveyStatsItem = new SurveyStatsItem();
        surveyStatsItem.setView(0);
        surveyStatsItem.setResponse(0);
        surveyStatsItem.setIDUser(idUser);
        surveyStatsItem.setStats(new HashMap<Short, QuestionStats>());
        SurveyStatsData.getInstance().setSurveyStatsItem(maxid, surveyStatsItem);
        dSurveyResult.setError(Error.SUCCESS);
        dSurveyResult.setIdSurvey(maxid);
        // update newlist
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Calendar cal = Calendar.getInstance();
        String today = dateFormat.format(cal.getTime());
        String beginday = dateFormat.format((long) surveyItem.getBeginDay() * 1000L);
        if (today.equalsIgnoreCase(beginday)) {
            IDSurveyNewData.getInstance().updateIDSurveyItem(idUser, maxid, Action.ADD);
        }
        long estimatedTime = new Date().getTime() - startTime;
        logger.debug(String.format("%s", estimatedTime));
        return dSurveyResult;
        //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error newResponse(int idUser, int idSurvey, Response response) throws TException {

        AnswersData answersData = AnswersData.getInstance();
        IDUserResponseData dUserResponseData = IDUserResponseData.getInstance();
        IDUserResponseNoRequiData dUserResponseNoRequiData = IDUserResponseNoRequiData.getInstance();
        ResponseData responseData = ResponseData.getInstance();

        List<AnswerItem> listAnswer = response.getAnswers();
        System.err.println("list Answer:" + listAnswer);
        listAnswer = Utility.trimListAnswers(listAnswer);
        System.err.println("list Answer:" + listAnswer);
        for (AnswerItem answer : listAnswer) {
            if (answersData.setAnswer(idUser, idSurvey, answer.idQues, answer) != Error.SUCCESS) {
                return Error.ERR_SYSTEM;
            }
            if (answer.require == false) {
                dUserResponseNoRequiData.updateIDUserResQuesNoRequi(idSurvey, answer.getIdQues(), idUser, Action.ADD);
            }
        }
        dUserResponseData.updateIDUserResponseItem(idSurvey, idUser, Action.ADD);
        // update state user
        if (responseData.setResponse(idSurvey, idUser, response) != Error.SUCCESS) {
            return Error.ERR_SYSTEM;
        }
        // update stats survey
        SurveyStatsItem surveyStatsItem = new SurveyStatsItem(0, 0, 1, new HashMap<Short, QuestionStats>());

        for (AnswerItem answer : listAnswer) {
            String[] choice = answer.getAnswer().split(",");
            QuestionStats questionStats = new QuestionStats();
            questionStats.setType(answer.getType());
            List<Integer> stats = new ArrayList<Integer>();
            // cho tung cau hoi chua làm
            if (answer.getType() == QuesType.SINGLE_LINE || answer.getType() == QuesType.MULTI_LINE) {
                stats.add(1);

            } else {
                for (String choice1 : choice) {
                    stats.add(Integer.parseInt(choice1));
                }
            }
            questionStats.setNumber(stats);

            surveyStatsItem.getStats().put(answer.idQues, questionStats);
        }
        if (SurveyStatsData.getInstance().updateSurveyStatsItem(idSurvey, surveyStatsItem) == Error.ERR_SYSTEM) {

            return Error.ERR_SYSTEM;
        }

        return Error.SUCCESS;

        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error updateSurvey(int idSurvey, SurveyItem surveyItem) throws TException {
        if (SurveyData.getInstance().replaceSurvey(idSurvey, surveyItem) == Error.ERR_SYSTEM) {
            return Error.ERR_SYSTEM;
        }
        DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
        Calendar cal = Calendar.getInstance();
        String today = dateFormat.format(cal.getTime());
        String beginday = dateFormat.format((long) surveyItem.getBeginDay() * 1000L);

        IDSurveyNewData.getInstance().updateIDSurveyItem(surveyItem.getIDUser(), idSurvey, Action.REMOVE);
        if (today.equalsIgnoreCase(beginday)) {

            IDSurveyNewData.getInstance().updateIDSurveyItem(surveyItem.getIDUser(), idSurvey, Action.ADD);
        }

        return Error.SUCCESS;
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Map<Short, Integer> listQuesCanEdit(int idSurvey) throws TException {
        Map<Short, Integer> listQues = new HashMap<Short, Integer>();
        SurveyItem surveyItem = null;
        surveyItem = SurveyData.getInstance().getSurvey(idSurvey);
        if (surveyItem == null) {
            return listQues;
        }

        SurveyStatsItem surveyStatsItem = null;
        surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idSurvey);

        if (surveyStatsItem == null) {
            surveyStatsItem = new SurveyStatsItem();
            surveyStatsItem.setView(0);
            surveyStatsItem.setResponse(0);
            SurveyStatsData.getInstance().setSurveyStatsItem(idSurvey, surveyStatsItem);
        }
        Map<Short, QuestionStats> mapquestionstats = surveyStatsItem.getStats();

        List<Question> list = surveyItem.getQuestions();
        for (Question question : list) {
            if (mapquestionstats == null) {
                listQues.put(question.getIdQues(), 0);

            } else {
                if (mapquestionstats.get(question.getIdQues()) == null) {
                    listQues.put(question.getIdQues(), 0);
                }

            }

        }
        return listQues;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<ShortInfoSurveyItem> getListShortInfoSurveyItem(int idUser, int page, int numOfpage, UserType usertype) throws TException {
        List<ShortInfoSurveyItem> list = new ArrayList<ShortInfoSurveyItem>();
        // get list idsurvey
        IDSurveyItem dSurveyItem = null;
        if (usertype == UserType.ADMIN) {
            dSurveyItem = IDSurveyData.getInstance().getIDSurveyItem(idUser);
        } else {
            dSurveyItem = IDSurveyNewData.getInstance().getIDSurveyItem(idUser);
        }

        if (dSurveyItem == null) {
            return list;
        }
        int begin = page * numOfpage;
        int end = begin + numOfpage;
        List<Integer> listIDSur = dSurveyItem.getIdSurveys();
        int sizeListIDSur = listIDSur.size();
        if ((sizeListIDSur / numOfpage) < (page - 1)) {
            return list;
        }
        if (sizeListIDSur < end) {
            end = sizeListIDSur;
        }
        for (int i = begin; i < end; i++) {
            int idsur = listIDSur.get(i);
            SurveyItem surveyItem = null;
            surveyItem = SurveyData.getInstance().getSurvey(idsur);
            if (surveyItem != null) {
                SurveyStatsItem surveyStatsItem = null;
                surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idsur);
                if (surveyStatsItem != null) {

                    list.add(new ShortInfoSurveyItem(idsur, surveyItem.status, surveyStatsItem.getView(), surveyStatsItem.getResponse(), surveyItem.getTitle(), surveyItem.getDescription(), surveyItem.option, surveyItem.getBeginDay(), surveyItem.getEndDay()));
                }

            }

        }

        return list;
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public SurveyItemResult getSurvey(int idSurvey) throws TException {
        SurveyItemResult itemResult = new SurveyItemResult();
        SurveyItem surveyItem = null;
        surveyItem = SurveyData.getInstance().getSurvey(idSurvey);
        if (surveyItem == null) {
            itemResult.setErro(Error.IDSURVEY_NO_EXITS);
            return itemResult;
        }
        itemResult.setErro(Error.SUCCESS);
        itemResult.setSurveyItem(surveyItem);
        return itemResult;
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int getCountSurvey(int idUser) throws TException {
        IDSurveyItem dSurveyItem = null;
        dSurveyItem = IDSurveyData.getInstance().getIDSurveyItem(idUser);
        if (dSurveyItem == null) {
            return 0;
        }
        return dSurveyItem.getCount();
        //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public String getResponse(int idSurvey, int idUser) throws TException {
        Response response = ResponseData.getInstance().getResponse(idSurvey, idUser);
        if (response == null) {
            return "";
        }
        SurveyItem surveyItem = SurveyData.getInstance().getSurvey(idSurvey);
        if (surveyItem == null) {
            return "";
        }
        return getResponseDetailBy(surveyItem, response);
        //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int getCountResponse(int idSurvey) throws TException {
        SurveyStatsItem surveyStatsItem = null;
        surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idSurvey);
        if (surveyStatsItem == null) {
            return 0;
        }
        return surveyStatsItem.getResponse();
        //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<Response> getListResponse(int idSurvey, int page, int numOfpage) throws TException {
        List<Response> listRespone = new ArrayList<Response>();
        IDUserResponseItem dUserResponseItem = null;
        dUserResponseItem = IDUserResponseData.getInstance().getIDUserResponseItem(idSurvey);
        if (dUserResponseItem == null) {
            return listRespone;
        }
        int begin = page * numOfpage;
        int end = begin + numOfpage;
        List<Integer> listIDUser = dUserResponseItem.getIdUsers();
        int sizeListIDUser = listIDUser.size();
        if ((sizeListIDUser / numOfpage) < (page - 1)) {
            return listRespone;
        }
        if (sizeListIDUser < end) {
            end = sizeListIDUser;
        }
        int idUser;
        Response response = null;
        for (int i = begin; i < end; i++) {
            idUser = listIDUser.get(i);
            response = ResponseData.getInstance().getResponse(idSurvey, idUser);
            if (response != null) {
                listRespone.add(response);
            }

        }

        return listRespone;

        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int getCountResByQues(int idSurvey, short idQues) throws TException {
        SurveyItem surveyItem = null;
        surveyItem = SurveyData.getInstance().getSurvey(idSurvey);
        if (surveyItem == null) {
            return 0;
        }
        List<Question> listQues = surveyItem.getQuestions();
        IDUserResponseItem dUserResponseItem = null;
        for (Question question : listQues) {
            if (question.getIdQues() == idQues) {
                if (question.require == true) {
                    dUserResponseItem = IDUserResponseData.getInstance().getIDUserResponseItem(idSurvey);
                    if (dUserResponseItem == null) {
                        return 0;
                    }
                    return dUserResponseItem.getIdUsers().size();
                } else {
                    dUserResponseItem = IDUserResponseNoRequiData.getInstance().getIDUserResQuesNoRequi(idSurvey, idQues);
                    if (dUserResponseItem == null) {
                        return 0;
                    }
                    return dUserResponseItem.getIdUsers().size();

                }

            }
        }
        return 0;

        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<AnswerItem> getResByQues(int idSurvey, short idQues, int page, int numOfpage) throws TException {
        List<AnswerItem> listAnswer = new ArrayList<AnswerItem>();
        SurveyItem surveyItem = null;
        surveyItem = SurveyData.getInstance().getSurvey(idSurvey);
        if (surveyItem == null) {
            return listAnswer;
        }

        List<Question> listQues = surveyItem.getQuestions();
        IDUserResponseItem dUserResponseItem = null;
        Question question1 = null;
        for (Question question : listQues) {
            if (question.getIdQues() == idQues) {
                if (question.require == true) {
                    dUserResponseItem = IDUserResponseData.getInstance().getIDUserResponseItem(idSurvey);
                } else {
                    dUserResponseItem = IDUserResponseNoRequiData.getInstance().getIDUserResQuesNoRequi(idSurvey, idQues);
                }

                question1 = new Question(question);
                break;

            }
        }
        if (dUserResponseItem != null) {
            int begin = page * numOfpage;
            int end = begin + numOfpage;
            List<Integer> listIDUser = dUserResponseItem.getIdUsers();
            int sizeListIDUser = listIDUser.size();
            if ((sizeListIDUser / numOfpage) < (page - 1)) {
                return listAnswer;
            }
            if (sizeListIDUser < end) {
                end = sizeListIDUser;
            }
            int idUser;
            AnswerItem answerItem = null;
            for (int i = begin; i < end; i++) {
                idUser = listIDUser.get(i);
                answerItem = AnswersData.getInstance().getAnswer(idUser, idSurvey, idQues);
                if (answerItem != null) {
                    if (question1.getType() == QuesType.MULTI_LINE) {
                        answerItem.setAnswer(String.format("%d-%d-%d", idUser, idSurvey, question1.getIdQues()));
                    }
                    listAnswer.add(answerItem);
                }

            }

        }
        return listAnswer;
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public SurveyStatsResult getSurveyStats(int idSurvey) throws TException {
        SurveyStatsResult surveyStatsResult = new SurveyStatsResult();
        SurveyStatsItem surveyStatsItem = null;
        surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idSurvey);
        if (surveyStatsItem == null) {
            surveyStatsResult.setErro(Error.IDSURVEY_NO_EXITS);
            return surveyStatsResult;
        }
        surveyStatsResult.setErro(Error.SUCCESS);
        surveyStatsResult.setSurveyStatsItem(surveyStatsItem);
        return surveyStatsResult;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public State checkUser(int idSurvey, int idUser) throws TException {
        System.out.println("id" + idSurvey + "user" + idUser);
        Response response = null;
        response = ResponseData.getInstance().getResponse(idSurvey, idUser);
        System.out.println("check user:" + response);
        if (response == null) {
            response = new Response(null, 0, null);
            ResponseData.getInstance().setResponse(idSurvey, idUser, response);
            SurveyStatsItem surveyStatsItem = new SurveyStatsItem(0, 1, 0, new HashMap<Short, QuestionStats>());
            SurveyStatsData.getInstance().updateSurveyStatsItem(idSurvey, surveyStatsItem);
            System.out.println("check use1r:" + response);
            return State.NEW;
        }
        if (response.getIdUser() == 0) {
            System.out.println("check user2:" + response);
            return State.VIEW;
        }
        System.out.println("check use3:" + response);
        return State.RESPONSE;
        //   throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<Error> removeListSurveyItem(List<Integer> idSurveys) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error removeResponse(int idSurvey, int idUser) throws TException {
        // get response
        ResponseData responseData = ResponseData.getInstance();
        Response response = null;
        response = responseData.getResponse(idSurvey, idUser);
        if (response == null) {
            return Error.RESPONSE_NO_EXITS;
        }
        List<AnswerItem> listAnswer = response.getAnswers();
        AnswersData answersData = AnswersData.getInstance();
        IDUserResponseData dUserResponseData = IDUserResponseData.getInstance();
        IDUserResponseNoRequiData dUserResponseNoRequiData = IDUserResponseNoRequiData.getInstance();
        for (AnswerItem answerItem : listAnswer) {
            short idQues = answerItem.getIdQues();
            answersData.removeAnswer(idUser, idSurvey, idQues);
            if (answerItem.require == false) {
                dUserResponseNoRequiData.updateIDUserResQuesNoRequi(idSurvey, idQues, idUser, Action.REMOVE);
            }
        }
        dUserResponseData.updateIDUserResponseItem(idSurvey, idUser, Action.REMOVE);
        IDUserResponseDelData.getInstance().updateIDUserResponseItem(idSurvey, idUser, Action.ADD);
        // update stats
        SurveyStatsItem statsItem = new SurveyStatsItem(1, 0, - 1, new HashMap<Short, QuestionStats>());
        listAnswer = Utility.trimListAnswers(listAnswer);
        for (AnswerItem answer : listAnswer) {
            String[] choice = answer.getAnswer().split(",");
            QuestionStats questionStats = new QuestionStats();
            questionStats.setType(answer.getType());
            List<Integer> stats = new ArrayList<Integer>();
            // cho tung cau hoi chua làm
            if (answer.getType() == QuesType.SINGLE_LINE || answer.getType() == QuesType.MULTI_LINE) {
                stats.add(-1);

            } else {
                for (String choice1 : choice) {
                    stats.add(Integer.parseInt(choice1.replace("1", "-1")));
                }
            }
            questionStats.setNumber(stats);

            statsItem.getStats().put(answer.idQues, questionStats);
        }

        SurveyStatsData.getInstance().updateSurveyStatsItem(idSurvey, statsItem);
        return Error.SUCCESS;
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error removeListResponse(List<ResponseKey> responseKey) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public String getStat(int type) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error removeSurveyItem(int idSurvey, int idUser) throws TException {
        SurveyData surveyData = SurveyData.getInstance();
        //IDSurveyData
        Error error = null;
        error = IDSurveyData.getInstance().updateIDSurveyItem(idUser, idSurvey, Action.REMOVE);
        if (error != Error.SUCCESS) {
            return error;
        }
        // remove hostlist and newlist
        IDSurveyHostData.getInstance().updateIDSurveyItem(idUser, idSurvey, Action.REMOVE);
        IDSurveyNewData.getInstance().updateIDSurveyItem(idUser, idSurvey, Action.REMOVE);

        SurveyItem surveyItem = surveyData.getSurvey(idSurvey);
        List<Question> questions = surveyItem.getQuestions();
        surveyData.removeSurvey(idSurvey);
        AnswersData answersData = AnswersData.getInstance();
        IDUserResponseData dUserResponseData = IDUserResponseData.getInstance();
        ResponseData responseData = ResponseData.getInstance();
        IDUserResponseItem dUserResponseItem = dUserResponseData.getIDUserResponseItem(idSurvey);
        IDUserResponseNoRequiData noRequiData = IDUserResponseNoRequiData.getInstance();
        if (dUserResponseItem != null) {
            List<Integer> idlList = dUserResponseItem.getIdUsers();
            for (Integer user : idlList) {
                for (Question question : questions) {
                    answersData.removeAnswer(user, idSurvey, question.getIdQues());
                }
                responseData.removeResponse(idSurvey, user);
            }
            dUserResponseData.removeResponseItem(idSurvey);
            for (Question question : questions) {
                noRequiData.removeIDUserResQuesNoRequi(idSurvey, question.getIdQues());
            }

        }
        dUserResponseItem = IDUserResponseDelData.getInstance().getIDUserResponseItem(idSurvey);
        if (dUserResponseItem != null) {
            List<Integer> idlList = dUserResponseItem.getIdUsers();
            for (Integer user : idlList) {
                for (Question question : questions) {
                    answersData.removeAnswer(user, idSurvey, question.getIdQues());
                }
                responseData.removeResponse(idSurvey, user);
            }
            dUserResponseData.removeResponseItem(idSurvey);
            for (Question question : questions) {
                noRequiData.removeIDUserResQuesNoRequi(idSurvey, question.getIdQues());
            }

        }
        SurveyStatsData.getInstance().removeSurveyStatsItem(idSurvey);

        return Error.SUCCESS;
    }

    @Override
    public List<ShortInfoSurveyItem> getListShortInfoSurveyItemHost(int idUser, int page, int numOfpage) throws TException {
        List<ShortInfoSurveyItem> list = new ArrayList<ShortInfoSurveyItem>();
        // get list idsurvey
        IDSurveyItem dSurveyItem = null;
        dSurveyItem = IDSurveyHostData.getInstance().getIDSurveyItem(idUser);
        if (dSurveyItem == null) {
            return list;
        }
        int begin = page * numOfpage;
        int end = begin + numOfpage;
        List<Integer> listIDSur = dSurveyItem.getIdSurveys();
        int sizeListIDSur = listIDSur.size();
        if ((sizeListIDSur / numOfpage) < (page - 1)) {
            return list;
        }
        if (sizeListIDSur < end) {
            end = sizeListIDSur;
        }
        for (int i = begin; i < end; i++) {
            int idsur = listIDSur.get(i);
            SurveyItem surveyItem = null;
            surveyItem = SurveyData.getInstance().getSurvey(idsur);
            if (surveyItem != null) {
                SurveyStatsItem surveyStatsItem = null;
                surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idsur);
                if (surveyStatsItem != null) {

                    list.add(new ShortInfoSurveyItem(idsur, surveyItem.status, surveyStatsItem.getView(), surveyStatsItem.getResponse(), surveyItem.getTitle(), surveyItem.getDescription(), surveyItem.isOption(), surveyItem.getBeginDay(), surveyItem.getEndDay()));
                }

            }

        }

        return list;
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<SurveyStatsPerDayItem> getListStatsSurveyPerDay(int idSurvey) throws TException {
        List<SurveyStatsPerDayItem> list = new ArrayList<SurveyStatsPerDayItem>();
        SurveyItemResult itemResult = getSurvey(idSurvey);
        if (itemResult.getErro() != Error.SUCCESS) {
            return list;
        }
        // get today
        Date today = TimeDay.getDate((int) (new Date().getTime() / 1000));
        Date begin = TimeDay.getDate(itemResult.getSurveyItem().getBeginDay());
        Date end = TimeDay.getDate(itemResult.getSurveyItem().getEndDay());

        SurveyStatsPerDayData statsPerDayData = SurveyStatsPerDayData.getInstance();
        if (begin.getTime() <= today.getTime()) {
            SurveyStatsPerDayItem statsPerDayItem;
            list.add(new SurveyStatsPerDayItem(0, 0, 0, 0, (int) (new Date(TimeDay.beforDay(begin).getTime()).getTime() / 1000)));
            while (begin.getTime() <= today.getTime() && begin.getTime() <= end.getTime()) {
                statsPerDayItem = statsPerDayData.getSurveyStatsPerDayItem(idSurvey, (int) (begin.getTime() / 1000));

                if (begin.getTime() == today.getTime() || begin.getTime() == end.getTime()) {
                    SurveyStatsItem statsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idSurvey);
                    statsPerDayItem = new SurveyStatsPerDayItem(statsItem.getView(), statsItem.getResponse(), 0, 0, (int) (begin.getTime() / 1000));
                } else if (statsPerDayItem == null) {
                    statsPerDayItem = new SurveyStatsPerDayItem(list.get(list.size() - 1));
                    statsPerDayItem.setDay((int) (begin.getTime() / 1000));
                }

                list.add(statsPerDayItem);

                begin = TimeDay.nextDay(begin);
            }

        }
        return list;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int getCountSurveyHost(int idUser) throws TException {
        IDSurveyItem dSurveyItem = null;
        dSurveyItem = IDSurveyHostData.getInstance().getIDSurveyItem(idUser);
        if (dSurveyItem == null) {
            return 0;
        }
        return dSurveyItem.getCount();
        //   throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public int getCountSurveyNew(int idUser) throws TException {
        IDSurveyItem dSurveyItem = null;
        dSurveyItem = IDSurveyNewData.getInstance().getIDSurveyItem(idUser);
        if (dSurveyItem == null) {
            return 0;
        }
        return dSurveyItem.getCount();
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public SurveyStatsAllItem getStatsAll(int idSurvey, int numOfpage) throws TException {
        SurveyStatsAllItem statsAllItem = new SurveyStatsAllItem();
        SurveyItem surveyItem = null;
        surveyItem = SurveyData.getInstance().getSurvey(idSurvey);
        if (surveyItem == null) {
            statsAllItem.setErro(Error.IDSURVEY_NO_EXITS);
            return statsAllItem;
        }
        statsAllItem.setErro(Error.SUCCESS);
        statsAllItem.setSurvey(surveyItem);
        //////////////////////////////////////////////////////
        SurveyStatsItem statsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idSurvey);
        if (statsItem == null) {
            statsAllItem.setErro(Error.IDSURVEY_NO_EXITS);
            return statsAllItem;
        }
        List<SurveyStatsPerDayItem> list = new ArrayList<SurveyStatsPerDayItem>();

        Date today = TimeDay.getDate((int) (new Date().getTime() / 1000));
        Date begin = TimeDay.getDate(surveyItem.getBeginDay());
        Date end = TimeDay.getDate(surveyItem.getEndDay());

        SurveyStatsPerDayData statsPerDayData = SurveyStatsPerDayData.getInstance();
        if (begin.getTime() <= today.getTime()) {
            SurveyStatsPerDayItem statsPerDayItem;
            list.add(new SurveyStatsPerDayItem(0, 0, 0, 0, (int) (new Date(TimeDay.beforDay(begin).getTime()).getTime() / 1000)));
            while (begin.getTime() <= today.getTime() && begin.getTime() <= end.getTime()) {
                statsPerDayItem = statsPerDayData.getSurveyStatsPerDayItem(idSurvey, (int) (begin.getTime() / 1000));

                if (begin.getTime() == today.getTime() || begin.getTime() == end.getTime()) {

                    statsPerDayItem = new SurveyStatsPerDayItem(statsItem.getView(), statsItem.getResponse(), 0, 0, (int) (begin.getTime() / 1000));
                } else if (statsPerDayItem == null) {
                    statsPerDayItem = new SurveyStatsPerDayItem(list.get(list.size() - 1));
                    statsPerDayItem.setDay((int) (begin.getTime() / 1000));
                }

                list.add(statsPerDayItem);

                begin = TimeDay.nextDay(begin);
            }

        }
        statsAllItem.setListStatPerDay(list);
        // stat
        statsAllItem.setSurveyStat(statsItem);
        //get listquest

        Map<Short, AnswerList> map = new HashMap<Short, AnswerList>();

        List<Question> listQuestions = surveyItem.getQuestions();
        IDUserResponseData dUserResponseData = IDUserResponseData.getInstance();
        IDUserResponseNoRequiData dUserResponseNoRequiData = IDUserResponseNoRequiData.getInstance();
        AnswersData answersData = AnswersData.getInstance();
        for (Question question : listQuestions) {
            if (question.getType() == QuesType.SINGLE_LINE || question.getType() == QuesType.MULTI_LINE) {
                List<AnswerItem> listAnswer = new ArrayList<AnswerItem>();
                IDUserResponseItem dUserResponseItem = null;
                int count = 0;
                if (question.require == true) {
                    dUserResponseItem = dUserResponseData.getIDUserResponseItem(idSurvey);
                } else {
                    dUserResponseItem = dUserResponseNoRequiData.getIDUserResQuesNoRequi(idSurvey, question.getIdQues());
                }

                if (dUserResponseItem != null) {
                    int endList = numOfpage;
                    List<Integer> listUser = dUserResponseItem.getIdUsers();
                    count = listUser.size();
                    if (count < numOfpage) {
                        endList = count;
                    }

                    for (int i = 0; i < endList; i++) {
                        AnswerItem answerItem = answersData.getAnswer(listUser.get(i), idSurvey, question.getIdQues());
                        if (question.getType() == QuesType.MULTI_LINE) {
                            answerItem.setAnswer(String.format("%d-%d-%d", listUser.get(i), idSurvey, question.getIdQues()));
                        }
                        listAnswer.add(answerItem);
                    }

                }

                AnswerList answerList = new AnswerList(listAnswer, count);
                map.put(question.getIdQues(), answerList);
            }
        }
        statsAllItem.setMapAnswerlist(map);
        return statsAllItem;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public List<Response> getListResponseByName(int idSurvey, String name) throws TException {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public ListShortInfoSurvey getgetListShortInfoSurveyAll(int idUser, int numOfpage, UserType usertype) throws TException {
        ListShortInfoSurvey listShortInfoSurvey = new ListShortInfoSurvey();
        List<ShortInfoSurveyItem> nlistew = new ArrayList<ShortInfoSurveyItem>();
        // get list idsurvey
        IDSurveyItem dSurveyItem = null;
        if (usertype == UserType.ADMIN) {
            dSurveyItem = IDSurveyData.getInstance().getIDSurveyItem(idUser);
        } else {
            dSurveyItem = IDSurveyNewData.getInstance().getIDSurveyItem(idUser);
        }

        if (dSurveyItem == null) {
            listShortInfoSurvey.setNewlist(nlistew);
            listShortInfoSurvey.setCountnew(0);
        } else {
            List<Integer> listIDSur = dSurveyItem.getIdSurveys();
            int count = listIDSur.size();
            int end = numOfpage;
            if (count < numOfpage) {
                end = count;
            }
            for (int i = 0; i < end; i++) {
                int idsur = listIDSur.get(i);
                SurveyItem surveyItem = null;
                surveyItem = SurveyData.getInstance().getSurvey(idsur);
                if (surveyItem != null) {
                    SurveyStatsItem surveyStatsItem = null;
                    surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idsur);
                    if (surveyStatsItem != null) {

                        nlistew.add(new ShortInfoSurveyItem(idsur, surveyItem.status, surveyStatsItem.getView(), surveyStatsItem.getResponse(), surveyItem.getTitle(), surveyItem.getDescription(), surveyItem.option, surveyItem.getBeginDay(), surveyItem.getEndDay()));
                    }

                }
            }
            listShortInfoSurvey.setNewlist(nlistew);
            listShortInfoSurvey.setCountnew(count);

        }
        List<ShortInfoSurveyItem> listhost = new ArrayList<ShortInfoSurveyItem>();
        // get list idsurvey
        dSurveyItem = null;
        dSurveyItem = IDSurveyHostData.getInstance().getIDSurveyItem(idUser);

        if (dSurveyItem == null) {
            listShortInfoSurvey.setHostlist(listhost);
            listShortInfoSurvey.setCounthost(0);
        } else {
            List<Integer> listIDSur = dSurveyItem.getIdSurveys();
            int count = listIDSur.size();
            int end = numOfpage;
            if (count < numOfpage) {
                end = count;
            }
            for (int i = 0; i < end; i++) {
                int idsur = listIDSur.get(i);
                SurveyItem surveyItem = null;
                surveyItem = SurveyData.getInstance().getSurvey(idsur);
                if (surveyItem != null) {
                    SurveyStatsItem surveyStatsItem = null;
                    surveyStatsItem = SurveyStatsData.getInstance().getSurveyStatsItem(idsur);
                    if (surveyStatsItem != null) {
                        listhost.add(new ShortInfoSurveyItem(idsur, surveyItem.status, surveyStatsItem.getView(), surveyStatsItem.getResponse(), surveyItem.getTitle(), surveyItem.getDescription(), surveyItem.option, surveyItem.getBeginDay(), surveyItem.getEndDay()));
                    }

                }
            }
            listShortInfoSurvey.setHostlist(listhost);
            listShortInfoSurvey.setCounthost(count);

        }

        return listShortInfoSurvey;

        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public Error addResponse(int idUser, int idSurvey, Response response, int idfan) throws TException {
        Response oldresponse = null;
        oldresponse = ResponseData.getInstance().getResponse(idSurvey, idUser);
        System.out.println("check user:" + oldresponse);
        if (oldresponse == null || oldresponse.getIdUser() == 0) {

            SurveyItem item = SurveyData.getInstance().getSurvey(idSurvey);
            if (item == null || item.getIDUser() != idfan) {
                return Error.IDSURVEY_NO_EXITS;
            }
            if (!Utility.validResponse(response.getAnswers(), item.getQuestions())) {
                return Error.ERR_SYSTEM;
            }

            // and
            AnswersData answersData = AnswersData.getInstance();
            IDUserResponseData dUserResponseData = IDUserResponseData.getInstance();
            IDUserResponseNoRequiData dUserResponseNoRequiData = IDUserResponseNoRequiData.getInstance();
            ResponseData responseData = ResponseData.getInstance();

            List<AnswerItem> listAnswer = response.getAnswers();

            listAnswer = Utility.trimListAnswers(listAnswer);

            for (AnswerItem answer : listAnswer) {
                if (answersData.setAnswer(idUser, idSurvey, answer.idQues, answer) != Error.SUCCESS) {
                    return Error.ERR_SYSTEM;
                }
                if (answer.require == false) {
                    dUserResponseNoRequiData.updateIDUserResQuesNoRequi(idSurvey, answer.getIdQues(), idUser, Action.ADD);
                }
            }
            dUserResponseData.updateIDUserResponseItem(idSurvey, idUser, Action.ADD);
            // update state user
            if (responseData.setResponse(idSurvey, idUser, response) != Error.SUCCESS) {
                return Error.ERR_SYSTEM;
            }
            // update stats survey
            SurveyStatsItem surveyStatsItem = null;
            if (oldresponse.getIdUser() == 0) {
                surveyStatsItem = new SurveyStatsItem(0, 0, 1, new HashMap<Short, QuestionStats>());
            } else {
                surveyStatsItem = new SurveyStatsItem(0, 1, 1, new HashMap<Short, QuestionStats>());
            }
            for (AnswerItem answer : listAnswer) {
                String[] choice = answer.getAnswer().split(",");
                QuestionStats questionStats = new QuestionStats();
                questionStats.setType(answer.getType());
                List<Integer> stats = new ArrayList<Integer>();
                // cho tung cau hoi chua làm
                if (answer.getType() == QuesType.SINGLE_LINE || answer.getType() == QuesType.MULTI_LINE) {
                    stats.add(1);

                } else {
                    for (String choice1 : choice) {
                        stats.add(Integer.parseInt(choice1));
                    }
                }
                questionStats.setNumber(stats);

                surveyStatsItem.getStats().put(answer.idQues, questionStats);
            }
            if (SurveyStatsData.getInstance().updateSurveyStatsItem(idSurvey, surveyStatsItem) == Error.ERR_SYSTEM) {

                return Error.ERR_SYSTEM;
            }

            return Error.SUCCESS;
        }

        return Error.IDUSER_ERR;
    }

    @Override
    public AnswerItem getAnswerItem(int idUser, int idSurvey, short idQues) throws TException {
        AnswerItem answerItem = AnswersData.getInstance().getAnswer(idUser, idSurvey, idQues);
        return answerItem;
        // throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    @Override
    public ListShortReponse getListShortResPonse(int idSurvey, int numOfpage) throws TException {
        ListShortReponse listShortReponse = new ListShortReponse(new ArrayList<ShortReponse>(), 0);
        IDUserResponseItem dUserResponseItem = null;
        dUserResponseItem = IDUserResponseData.getInstance().getIDUserResponseItem(idSurvey);
        if (dUserResponseItem == null) {
            return listShortReponse;
        }
        List<Integer> listIDUser = dUserResponseItem.getIdUsers();
        int end = numOfpage;
        int count = listIDUser.size();
        if (count < numOfpage) {
            end = count;
        }
        ResponseData responseData = ResponseData.getInstance();
        List<ShortReponse> shortReponses = new ArrayList<>();
        Response response = null;
        int idUser;
        for (int i = 0; i < end; i++) {
            idUser = listIDUser.get(i);
            response = responseData.getResponse(idSurvey, idUser);
            if (response != null) {
                shortReponses.add(new ShortReponse(String.format("%d-%d", idSurvey, idUser), idUser, response.getDisplayName(), response.getAnswers().get(0).getTimeResponse()));
            }

        }
        listShortReponse.setListshortResponse(shortReponses);
        listShortReponse.setCount(count);
        return listShortReponse;
        //throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

    private String getResponseDetailBy(SurveyItem surveyItem, Response response) {
        String result = "";
        ResponeDetail detail = new ResponeDetail();
        detail.setTitle(surveyItem.getTitle());
        List<AnswerItem> listAnswers = response.getAnswers();
        List<Question> listQuestion = surveyItem.getQuestions();
        List<AnswerDetail> listAnswerDetail = new ArrayList<AnswerDetail>();
        AnswerDetail answerDetail;

        for (Question question : listQuestion) {
            AnswerItem answerItem = Utility.getAnswerItemById(question.getIdQues(), listAnswers);
            List<String> choice = new ArrayList<String>();
            List<String> answer = new ArrayList<String>();

            if (question.getType() == QuesType.SINGLE_LINE || question.getType() == QuesType.SINGLE_LINE) {
                if (answerItem == null) {
                    answer.add("");
                } else {
                    answer.add(answerItem.getAnswer());
                }
                choice.add("");
            } else {
                if (answerItem == null) {
                    for (int i = 0; i < question.getChoices().size(); i++) {
                        answer.add("0");
                    }
                } else {
                    answer = Arrays.asList(answerItem.getAnswer().split(","));
                }
                choice = question.getChoices();
//                if (choice.size() > answer.size()) {
//                    do {
//                        answer.add("0");
//                    } while (choice.size() > answer.size());
//
//                } else if (choice.size() < answer.size()) {
//                    do {
//                        answer.remove(answer.size() - 1);
//                    } while (choice.size() < answer.size());
//
//                }

            }

            answerDetail = new AnswerDetail(question.getTitleQues(), question.require, question.getType(), choice, answer);

            listAnswerDetail.add(answerDetail);
        }
        Gson gson = new Gson();
        detail.setAnswers(listAnswerDetail);
        System.out.println(gson.toJson(detail));
        return gson.toJson(detail);
    }


    @Override
    public List<ShortReponse> getListShortResponse(int idSurvey, int page, int numOfpage) throws TException {
        List<ShortReponse> shortReponses = new ArrayList<ShortReponse>();   
        IDUserResponseItem dUserResponseItem = null;
        dUserResponseItem = IDUserResponseData.getInstance().getIDUserResponseItem(idSurvey);
        if (dUserResponseItem == null) {
            return shortReponses;
        }
        int begin = page * numOfpage;
        int end = begin + numOfpage;
        List<Integer> listIDUser = dUserResponseItem.getIdUsers();
        int sizeListIDUser = listIDUser.size();
        if ((sizeListIDUser / numOfpage) < (page - 1)) {
            return shortReponses;
        }
        if (sizeListIDUser < end) {
            end = sizeListIDUser;
        }
        int idUser;
        Response response = null;
        for (int i = begin; i < end; i++) {
            idUser = listIDUser.get(i);
            response = ResponseData.getInstance().getResponse(idSurvey, idUser);
            if (response != null) {
                shortReponses.add(new ShortReponse(String.format("%d-%d", idSurvey,idUser), idUser, response.getDisplayName(),response.getAnswers().get(0).getTimeResponse()));
            }

        }
        return shortReponses;
      //  throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }


}
